package com.lanou3g.musicenjoy.activities;

import android.app.Activity;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;

import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;

import android.widget.AdapterView;

import android.widget.ImageButton;
import android.widget.ImageView;

import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.lanou3g.musicenjoy.R;
import com.lanou3g.musicenjoy.adapter.LyricAdapter;
import com.lanou3g.musicenjoy.adapter.PlayMenuAdapter;
import com.lanou3g.musicenjoy.application.MusicApplication;

import com.lanou3g.musicenjoy.entity.PlayMusicEntity;


import com.lanou3g.musicenjoy.entity.greendao.MusicInfoBean;
import com.lanou3g.musicenjoy.entity.greendao.MusicInfoBeanDao;
import com.lanou3g.musicenjoy.eventbus.MyEvent;

import com.lanou3g.musicenjoy.loadlyric.LyricDownloadManager;
import com.lanou3g.musicenjoy.loadlyric.LyricLoadHelper;
import com.lanou3g.musicenjoy.loadlyric.LyricSentence;

import com.lanou3g.musicenjoy.greendao.DaoSingleton;

import com.lanou3g.musicenjoy.service.OnlineService;

import com.lanou3g.musicenjoy.utils.Time;
import com.squareup.picasso.Picasso;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.dao.query.DeleteQuery;
import de.greenrobot.dao.query.QueryBuilder;
import de.greenrobot.event.EventBus;


/**
 * Created by 辛鑫 on 15/11/2.
 * 播放音乐主界面
 */
public class PlayerActivity extends Activity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {
    private ImageView play_share;
    ImageView mainPlayImg;
    ImageView mainPlayPop;
    ImageView mainPlayBack;
    TextView mainPlaySongName;
    TextView mainSingerName;
    ImageButton lastBtn;
    ImageButton playBtn;
    ImageButton nextBtn;
    ImageButton playStatic;
    ImageButton playList;
    TextView lyric_empty;
    ListView lyric_listView;
    static TextView currentTime;
    SeekBar playSeekBar;

    //李宁
    private ImageView play_collect, play_songlist;//我的收藏,歌单
    private MusicInfoBean info;//实体类
    private ArrayList<MusicInfoBean> infos;
    private QueryBuilder<MusicInfoBean> queryBuilder;
    private MusicInfoBeanDao musicInfoBeanDao;//表
    private DaoSingleton daoSingleton;
   // private OnlineService.MediaBinder mediaBinder;//查询数据库表用

    private ListView listView;
    private PlayMenuAdapter playMenuAdapter;
    private TextView clearAll;
    private int a = 0;

    private LyricLoadHelper mLyricLoadHelper;
    private LyricDownloadManager mLyricDownloadManager;


    // private Song song;
    private int currentState = 0;
    static TextView mainPlayTime;
    private List<PlayMusicEntity> data;
    private OnlineService.MediaBinder mediaBinder;

    private MyThread mThread;

    private int index=0;//从listview中获取点击的位置才传给分享

    private int function = 0;//0:顺序播放 1:单曲播放 2:循环播放 3:随机播放

    /**
     * 歌词是否正在下载
     */
    private boolean mIsLyricDownloading;

    private LyricAdapter mLyricAdapter;

    private int[] staticBtns = {R.mipmap.img_appwidget91_playmode_normal, R.mipmap.img_appwidget91_playmode_repeat_current, R.mipmap.img_appwidget91_playmode_repeat_all,
            R.mipmap.img_appwidget91_playmode_shuffle};
    private String[] staticName = {"顺序播放", "单曲循环", "循环播放", "随机播放"};

    private int[] startBtn = {R.mipmap.bt_widget_pause_press, R.mipmap.bt_widget_play_press};//0:播放 1:暂停
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mediaBinder = (OnlineService.MediaBinder) service;

            //通知service已开启activity
            EventBus.getDefault().post(new MyEvent.isStart(true));
            //将当前的状态发送给服务
            EventBus.getDefault().post(new MyEvent.RecycleMode(function));
            Log.i("syso", "通知服务已开启activity");
            Log.i("syso", "连接成功");

            if (mediaBinder.isPlaying()) {

                playBtn.setImageResource(startBtn[0]);
                Log.i("xxx", "当前正在播放");


            } else {
                playBtn.setImageResource(startBtn[1]);
                Log.i("xxx", "当前没有在播放");
                //lyric_empty.setVisibility(View.VISIBLE);
            }


            mainPlayTime.setText(Time.formatTime((long) mediaBinder.getDuration()));
            mThread.start();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mainplay_layout);
        mThread = new MyThread();
        Log.i("syso", "进入onCreare方法");
        play_share= (ImageView) findViewById(R.id.play_share);
        mainPlayImg = (ImageView) findViewById(R.id.main_play_img);
        mainPlayPop = (ImageView) findViewById(R.id.main_play_pop);
        mainPlayBack = (ImageView) findViewById(R.id.main_play_back);
        mainPlaySongName = (TextView) findViewById(R.id.main_play_songName);
        mainSingerName = (TextView) findViewById(R.id.main_singerName);
        lastBtn = (ImageButton) findViewById(R.id.lastBtn);
        playBtn = (ImageButton) findViewById(R.id.playBtn);
        nextBtn = (ImageButton) findViewById(R.id.nextBtn);
        currentTime = (TextView) findViewById(R.id.current_time);
        playSeekBar = (SeekBar) findViewById(R.id.play_seekBar);
        mainPlayTime = (TextView) findViewById(R.id.main_play_time);
        playStatic = (ImageButton) findViewById(R.id.play_static);
        playList = (ImageButton) findViewById(R.id.play_list);

        lyric_listView = (ListView) findViewById(R.id.lyric_listView);
        lyric_empty = (TextView) findViewById(R.id.lyric_empty);
        mLyricLoadHelper = new LyricLoadHelper();
        mLyricDownloadManager = new LyricDownloadManager(this);
        mLyricLoadHelper.setLyricListener(mLyricListener);
        mLyricAdapter = new LyricAdapter(this);

        //李宁
        play_collect = (ImageView) findViewById(R.id.play_collect);//收藏到我的最爱
//        play_songlist = (ImageView) findViewById(R.id.play_songlist);//歌单
        //李宁 dao初始化
        daoSingleton = DaoSingleton.getInstance();
        musicInfoBeanDao = daoSingleton.getMusicInfoBeanDao();
        queryBuilder = musicInfoBeanDao.queryBuilder();


        data = new ArrayList<>();
        EventBus.getDefault().register(this);
        Intent intent = new Intent(this, OnlineService.class);
        bindService(intent, connection, BIND_AUTO_CREATE);
        //监听
        play_share.setOnClickListener(this);
        mainPlayPop.setOnClickListener(this);
        mainPlayBack.setOnClickListener(this);
        lastBtn.setOnClickListener(this);
        playBtn.setOnClickListener(this);
        nextBtn.setOnClickListener(this);
        playList.setOnClickListener(this);
        lyric_empty.setOnClickListener(this);
        playSeekBar.setOnSeekBarChangeListener(this);
        // initData();

        playList.setOnClickListener(this);
        playStatic.setOnClickListener(this);

        //李宁
        play_collect.setOnClickListener(this);//收藏到我的最爱
//        play_songlist.setOnClickListener(this);//我的歌单

        Log.i("tttt", function + "");
        SharedPreferences sharedPreferences = getSharedPreferences("shuju", MODE_PRIVATE);
        function = sharedPreferences.getInt("sss", 0);
        Picasso.with(this).load(staticBtns[function]).into(playStatic);
        EventBus.getDefault().post(new MyEvent.RecycleMode(function));
        Log.i("static", "当前状态" + staticName[function]);
        lyric_listView.setAdapter(mLyricAdapter);

    }


    //view的改变需要下主线程中进行
    //通过handler不断刷新当前进度
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            currentTime.setText(Time.formatTime((long) msg.arg1));
            //Log.i("xxxx", msg.arg1 + "");
            mLyricLoadHelper.notifyTime((long)msg.arg1);
            // mainPlayTime.setText(Time.formatTime((long) msg.arg2));
        }
    };


    //接受顺序播放时完成最后一首时服务发送过来的消息
    public void onEvent(MyEvent.IsFinish event) {
        mThread.stop();
        playBtn.setImageResource(startBtn[1]);
        currentTime.setText(Time.formatTime((long) 0));
        mainPlayTime.setText(Time.formatTime((long) 0));
        playSeekBar.setProgress(0);
        Log.i("syso", "设置数据完成");
    }

    // 接受从服务传递过来的数据
    public void onEvent(MyEvent.Isplay event) {

        if (event.isPlay() == true) {
            Log.i("syso", "接受服务数据成功000");
            setData();
            mainPlayTime.setText(Time.formatTime((long) mediaBinder.getDuration()));

        }

    }

    //一首歌曲自动播放完成时接受消息
    public void onEvent(MyEvent.AutoNext evevnt) {
        setData();
        mainPlayTime.setText(Time.formatTime((long) mediaBinder.getDuration()));
    }

    //播放列表接收从服务传递过来的数据
    public void onEvent(MyEvent.PlayMenu event) {

        data = (List<PlayMusicEntity>) event.getSongMenu();
        index=event.getA();
        Log.i("fajfajf",index+"");
        info.setUrl(data.get(mediaBinder.getPosition()).getUrl());

        Log.i("playMenu", data.get(0).getSingerName());
        Log.i("dddd", data + "");
    }

    private void setData() {
        Log.i("iii", "开始设置数据");
        if (mediaBinder != null && mediaBinder.getSingerName() != null) {
            mainSingerName.setText(mediaBinder.getSingerName());
            mainPlaySongName.setText(mediaBinder.getSongName());
            info = new MusicInfoBean();
            info.setSongname(mediaBinder.getSongName());
            info.setSinger(mediaBinder.getSingerName());
            info.setPicUrl(mediaBinder.getPicture());
            lyric_listView.setVisibility(View.VISIBLE);
            lyric_empty.setVisibility(View.GONE);
            Log.i("xxx", "当前有数据");
            loadLyricByHand(mediaBinder.getSongName(), mediaBinder.getSingerName());

            Log.i("iii", info + "");

            Picasso.with(this).load(mediaBinder.getPicture()).into(mainPlayImg);

        } else {

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lyric_empty:
                break;
            case R.id.main_play_pop:
                break;
            case R.id.play_list:
                currentState++;

                PopupWindow window = new PopupWindow(this);
                if (currentState % 2 != 0) {
                    Log.i("fjas", "nidianjiel ");

                    View view = getLayoutInflater().inflate(R.layout.fragment_paly, null);

                    listView = (ListView) view.findViewById(R.id.playListView);
                    clearAll = (TextView) view.findViewById(R.id.clearAll);
                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            //index=position;
                           EventBus.getDefault().post(new MyEvent.PassData(data,position));

                        }
                    });
                    clearAll.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            a = 1;
                        }
                    });

                    playMenuAdapter = new PlayMenuAdapter(this, data);

                    Log.i("fjlaskj", data + "");
                    listView.setAdapter(playMenuAdapter);
                    window.setContentView(view);
                    window.setOutsideTouchable(true);
                    window.setWidth(420);
                    window.setHeight(580);
                    window.setFocusable(true);
                    window.showAtLocation(v, Gravity.BOTTOM, 100, 80);
                } else {
                    window.dismiss();
                }


                break;
            case R.id.play_static:
                if (function + 1 < 4) {
                    function++;
                } else {
                    function = 0;
                }

                EventBus.getDefault().post(new MyEvent.RecycleMode(function));
                Picasso.with(this).load(staticBtns[function]).into(playStatic);
                Toast.makeText(PlayerActivity.this, staticName[function], Toast.LENGTH_SHORT).show();


                break;
            case R.id.main_play_back:
                finish();
                break;
            case R.id.lastBtn:
                mediaBinder.previousSong();
                setData();
                //点击上一首通知播放栏
                EventBus.getDefault().post(new MyEvent.IsNext(true));
                break;
            case R.id.playBtn:

                if (mediaBinder.isPlaying()) {
                    playBtn.setImageResource(startBtn[1]);
                    Toast.makeText(PlayerActivity.this, "已暂停", Toast.LENGTH_SHORT).show();
                    mediaBinder.pause();
                    Log.i("xxx", "点击了暂停");

                } else if (!mediaBinder.isPlaying() && mediaBinder.getDuration() > mediaBinder.getCurrentPosition()) {
                    playBtn.setImageResource(startBtn[0]);
                    Toast.makeText(PlayerActivity.this, "正在播放", Toast.LENGTH_SHORT).show();
                    mediaBinder.start();
                    Log.i("xxx", "点击了播放");

                } else {
                    Toast.makeText(PlayerActivity.this, "请选择要播放的歌曲", Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.nextBtn:
                mediaBinder.nextSong();
                //点击下一首时通知播放条
                EventBus.getDefault().post(new MyEvent.IsNext(true));
                setData();

                break;
            case R.id.play_share:
                if (data!=null&&data.size()>0) {
                    //分享监听
                    // 首先在您的Activity中添加如下成员变量
                    final UMSocialService mController = UMServiceFactory.getUMSocialService("http://www.liwushuo.com/credit/invitation?code=tp23io");
                    // 设置分享内容
                    mController.setShareContent("邀请你一起共享音乐");
                    // 设置分享图片, 参数2为图片的url地址
                    Log.i("fjjjjj", mediaBinder.getPosition() + "");
                    mController.setShareMedia(new UMImage(this,
                            data.get(mediaBinder.getPosition()).getUrl()));
                    mController.getConfig().removePlatform(SHARE_MEDIA.RENREN, SHARE_MEDIA.DOUBAN);

                    //参数1为当前Activity，参数2为开发者在QQ互联申请的APP ID，参数3为开发者在QQ互联申请的APP kEY.
                    UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(PlayerActivity.this, "100424468",
                            "c7394704798a158208a74ab60104f0ba");
                    qqSsoHandler.addToSocialSDK();

                    //参数1为当前Activity，参数2为开发者在QQ互联申请的APP ID，参数3为开发者在QQ互联申请的APP kEY.
                    QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(PlayerActivity.this, "100424468",
                            "c7394704798a158208a74ab60104f0ba");
                    qZoneSsoHandler.addToSocialSDK();
                    mController.openShare(PlayerActivity.this, false);
                    //新浪分享
                    mController.getConfig().setSsoHandler(new SinaSsoHandler());
                }else {
                    Toast.makeText(this,"你TMsb啊,你播放音乐了吗?啊?",Toast.LENGTH_SHORT).show();
                }
                break;
            //李宁收藏到我的最爱
            case R.id.play_collect:

                if (info==null){
                    Toast.makeText(this,"当前无音乐",Toast.LENGTH_SHORT).show();
                }else {
                    infos = (ArrayList<MusicInfoBean>) queryBuilder.where(MusicInfoBeanDao.Properties.Songname.eq(mediaBinder.getSongName())).list();
                    if (infos == null || infos.size() == 0) {

                        MusicInfoBean musicInfoBean = new MusicInfoBean();
                        musicInfoBean = info;
                       // Log.i("musicInfoBean", musicInfoBean + "");
                        musicInfoBean.setSongname(mediaBinder.getSongName());
                        musicInfoBeanDao.insert(musicInfoBean);
                        Log.i("xxx", musicInfoBean.getSongname());
                        //Log.i("xxx", musicInfoBean.)
                        Toast.makeText(this, "收藏成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, "取消收藏", Toast.LENGTH_SHORT).show();
                        DeleteQuery<MusicInfoBean> deleteQuery = queryBuilder.where(MusicInfoBeanDao.Properties.Songname.eq(mediaBinder.getSongName())).buildDelete();
                        deleteQuery.executeDeleteWithoutDetachingEntities();
                    }
                }
                break;
//            case R.id.play_songlist://我的歌单
//
//                break;
        }
    }

    private void loadLyricByHand(String musicName, String artist) {
        // 取得歌曲同目录下的歌词文件绝对路径
        String lyricFilePath = MusicApplication.lrcPath + "/" + musicName + ".lrc";
        File lyricfile = new File(lyricFilePath);

        if (lyricfile.exists()) {
            // 本地有歌词，直接读取
            // Log.i(TAG, "loadLyric()--->本地有歌词，直接读取");
            mLyricLoadHelper.loadLyric(lyricFilePath);
        } else {
            mIsLyricDownloading = true;
            // 尝试网络获取歌词
            // Log.i(TAG, "loadLyric()--->本地无歌词，尝试从网络获取");
            new LyricDownloadAsyncTask().execute(musicName, artist);

        }
    }

    //异步任务后台下载歌词
    class LyricDownloadAsyncTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            // 从网络获取歌词，然后保存到本地
            String lyricFilePath = mLyricDownloadManager.searchLyricFromWeb(
                    params[0], params[1]);
            // 返回本地歌词路径
            mIsLyricDownloading = false;
            return lyricFilePath;
        }

        @Override
        protected void onPostExecute(String result) {
            // Log.i(TAG, "网络获取歌词完毕，歌词保存路径:" + result);
            // 读取保存到本地的歌曲
            mLyricLoadHelper.loadLyric(result);
        }

    }

    private LyricLoadHelper.LyricListener mLyricListener = new LyricLoadHelper.LyricListener() {

        @Override
        public void onLyricLoaded(List<LyricSentence> lyricSentences, int index) {
            // Log.i(TAG, "onLyricLoaded");
            if (lyricSentences != null) {
                // Log.i(TAG, "onLyricLoaded--->歌词句子数目=" + lyricSentences.size()
                // + ",当前句子索引=" + index);
                mLyricAdapter.setLyric(lyricSentences);
                mLyricAdapter.setCurrentSentenceIndex(index);
                mLyricAdapter.notifyDataSetChanged();
                // 本方法执行时，lyricshow的控件还没有加载完成，所以延迟下再执行相关命令
                // mHandler.sendMessageDelayed(
                // Message.obtain(null, MSG_SET_LYRIC_INDEX, index, 0),
                // 100);
            }
        }

        //歌曲播放时歌词的改变状态
        @Override
        public void onLyricSentenceChanged(int indexOfCurSentence) {
            mLyricAdapter.setCurrentSentenceIndex(indexOfCurSentence);
            mLyricAdapter.notifyDataSetChanged();
            lyric_listView.smoothScrollToPositionFromTop(indexOfCurSentence,
                    lyric_listView.getHeight() / 2, 500);
        }

    };



    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        //当处于暂停状态时改变进度条位置时, 改变button的图片
        if (progress != mediaBinder.getCurrentPosition() &&
                mediaBinder.getCurrentPosition() != mediaBinder.getDuration()) {
            playBtn.setImageResource(R.mipmap.bt_widget_pause_press);
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        if (mediaBinder != null) {
            //设置音乐播放进度
            mediaBinder.seekTo(seekBar.getProgress());

        }
    }


    //不断获得当前播放进度
    class MyThread extends Thread {
        @Override
        public void run() {
            super.run();
            int max = mediaBinder.getDuration();
            playSeekBar.setMax(max);
            Log.i("max", "当前最大值" + max);
            // mainPlayTime.setText(Time.formatTime((long) max));
            while (true && mediaBinder != null) {

                int position = mediaBinder.getCurrentPosition();

                //设置当前进度
                playSeekBar.setProgress(position);
                Message msg = new Message();
                msg.arg1 = position;
                msg.arg2 = max;
                mHandler.sendMessage(msg);
                // mHandler.sendEmptyMessage(position);
                //每取一次进度值稍微睡200毫秒
                try {
                    sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        //解除绑定
        unbindService(connection);
        Log.i("SSS", "进入onDestroy方法");
        mediaBinder = null;
        SharedPreferences sharedPreferences = getSharedPreferences("shuju", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("sss", function);
        editor.commit();
        editor.clear();
    }

}
